package com.itheima.controller;

import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;

//    @RequestMapping(value = "/depts", method = RequestMethod.GET)
    @GetMapping("/depts")
    public Result list() {
        System.out.println("查询全部部门数据");

        List<Dept> deptList = deptService.findAll();
        Result result = Result.success(deptList);

        return result;
    }

    @DeleteMapping("/depts")
    public Result deleteById(HttpServletRequest request) {
        String strId = request.getParameter("id");
        int id = Integer.parseInt(strId);
        System.out.println("删除id为" + id + "的数据");

        int result = deptService.deleteById(id);

        if(result == 1) {
            return Result.success();
        } else {
            return Result.error("删除失败");
        }
    }


    @PostMapping("/depts")
    public Result insertData(@RequestBody Dept dept) {

        int result = deptService.insertData(dept);
        if(result == 1) {
            return Result.success();
        } else {
            return Result.error("插入失败");
        }
    }

    @GetMapping("/depts/{id}")
    public Result findById(@PathVariable int id) {
        Dept dept = deptService.findById(id);
        return Result.success(dept);
    }

    @PutMapping("/depts")
    public Result update(@RequestBody Dept dept) {

        deptService.update(dept);
        return Result.success();
    }

}
